class Ad {
  constructor(options) {
    this.$options = Object.assign(
      {
        time: 10,
      },
      options
    );
    // 广告的标签元素
    this.$el = document.querySelector(this.$options.el);
    this.$el.style.position = "fixed";

    //移动方向
    this.x = this.y = 1;

    //定时执行动画
    this.intervalId = setInterval(this.run.bind(this), this.$options.time);

    // setTimeout(
    //   () => clearInterval(window.clearInterval(this.intervalId)),
    //   2000
    // );
    //
    this.bindEvent();
  }

  bindEvent() {
    this.$el.addEventListener("mouseover", () => {
      clearInterval(this.intervalId);
    });
  }

  // 定时器执行函数
  run() {
    this.$el.style.left = this.left() + "px";
    this.$el.style.top = this.top() + "px";
  }

  left() {
    const { x, width } = this.$el.getBoundingClientRect();
    const { clientWidth } = document.documentElement;
    if (x + width > clientWidth) this.x = -1;
    if (x < 0) this.x = 1;
    return x + this.x;
  }

  top() {
    const { y, height } = this.$el.getBoundingClientRect();
    const { clientHeight } = document.documentElement;

    if (y + height > clientHeight) this.y = -1;
    if (y < 0) this.y = 1;

    return y + this.y;
  }
}

export default (options) => new Ad(options);
